package boun.swe.bob.service;

import boun.swe.bob.entities.User;
import boun.swe.bob.util.RandomPassword;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * This controller is used for forgot password page actions 
 */
public class ForgotPasswordController extends BaseController {

    /**
     * Shows the page
     *
     * @param httpServletRequest http request
     * @param httpServletResponse http response
     * @return page
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showPage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        return new ModelAndView("forgotPassword");
    }

    /**
     * Handles HTTP POST action
     *
     * @param httpServletRequest http request
     * @param httpServletResponse http response
     * @return the result message
     */
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView processRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map<String, Object> model = Maps.newHashMap();
        String username = httpServletRequest.getParameter("username");
        if (!Strings.isNullOrEmpty(username)) {
            String newPassword = RandomPassword.getRandomString(6);
            String md5Password = userDao.createMd5Password(newPassword);
            User user = userDao.findByUsername(username);
            if (null != user) {
                user.setPassword(md5Password);
                userDao.merge(user);
                System.out.println("Mail is sent to: " + username + " with new password: " + newPassword);
                mailSender.send(user.getUsername(), "New BOB password", "Your new BOB password is: " + newPassword);
                model.put("message", "Your new password is sent to your email...");
            } else {
                model.put("message", "Not existing user...");
            }

        } else {
            model.put("message", "Invalid username...");
        }
        return new ModelAndView("forgotPassword", "model", model);
    }


}
